package cn.tedu.vrd08.controller;

import cn.tedu.vrd08.entity.Banner;
import cn.tedu.vrd08.mapper.BannerMapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
public class BannerController {
    @Autowired(required = false)
    BannerMapper mapper;

    @RequestMapping("/banner/select")
    public List<Banner> select() {
        return mapper.select();
    }

    @RequestMapping("/banner/add")
    public void add(MultipartFile picFile) throws IOException {
        String fileName=picFile.getOriginalFilename();
        String suffix=fileName.substring(fileName.lastIndexOf("."));
        fileName= UUID.randomUUID()+suffix;
        String dirPath="E:/upload/";
        File dirFile=new File(dirPath);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        String filePath=dirPath+fileName;
        picFile.transferTo(new File(filePath));
        //把轮播图数据保存到数据库里
        Banner banner=new Banner();
        banner.setUrl("/"+fileName);
        mapper.insert(banner);
    }

    @RequestMapping("/banner/delete")
    public void delete(int id) {
        String url=mapper.selectUrlById(id);
        String filePath="E:/upload"+url;
        new File(filePath).delete();
        mapper.delete(id);
    }
}
